<!-- ArticleList.vue -->
<!--文章列表页组件-->
<template>
  <div class="main">
    <div v-if="loading">正在加载文章列表...</div>
    <!-- 文章列表 -->
    <ul v-else-if="articles.length > 0" class="article-list">
      <li v-for="article in articles" :key="article.id" class="article-item">
        <el-tooltip placement="bottom" effect="light" :content="article.title" :visible-arrow="false"
                    :open-delay="1000">
        <router-link :to="`${$route.path}/details/${article.article_id}`">
          {{ truncatedTitle(article.title) }}
        </router-link>
          </el-tooltip>
        <span class="publish-date">{{ formatDate(article.publish_date) }}</span>
      </li>
      <!--翻页组件-->
      <div class="transfer">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="15"
          layout="total, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </ul>
    <div v-else class="no-articles">暂无文章。</div>
  </div>
</template>

<script>
import service from "@/utils/service";
import { mapMutations, mapState } from "vuex"; //vuex中的辅助函数

export default {
  data() {
    return {
      articles: [], //文章列表
      currentPage: 1, // 初始化当前页码为1
      loading: false, // 添加 loading 状态
      currentColumnName: "",
    };
  },

  computed: {
    ...mapState(["subColumns",'total']), //从vuex中传递过来的子栏目
  },
  created(){
    if(this.$route.query.page){
      this.currentPage = Number(this.$route.query.page);
    }else {
      this.currentPage = 1;
    }

    if (this.subColumns.length > 0) {
      const subColumnPath = this.$route.path;

      const matchingSubColumn = this.subColumns.find(
        (sub) => sub.path === subColumnPath
      );
      if (matchingSubColumn) {
        this.currentColumnName = matchingSubColumn.name;
        this.fetchArticleList(matchingSubColumn.subcolumn_id);
        this.fetchArticleTotal(matchingSubColumn.subcolumn_id);
      }
    }

  },
  watch: {
    // //处理页面刷新
    // subColumns: {
    //   handler(newSubColumns) {
    //     console.log(112);
    //     if (newSubColumns.length > 0) {
    //       const subColumnPath = this.$route.path;
    //       const matchingSubColumn = newSubColumns.find(
    //         (sub) => sub.path === subColumnPath
    //       );
    //       if (matchingSubColumn) {
    //         this.currentColumnName = matchingSubColumn.name;
    //         this.fetchArticleList(matchingSubColumn.name);
    //         this.fetchArticleTotal(matchingSubColumn.name);
    //       }
    //     }
    //   },
    //   immediate: true,
    // },
    // $route: {
    //   handler(to, from) {
    //     console.log('这里是第二次监听');
    //     console.log('to',to);
    //     console.log('from',from);
    //     if (this.subColumns.length > 0) {
    //       const subColumnPath = to.path; // 获取当前路由的路径
    //       console.log('当前的路径',subColumnPath);
    //       const matchingSubColumn = this.subColumns.find(
    //         (sub) => sub.path === subColumnPath
    //       );
    //
    //       if(typeof from === "undefined"){//处理刷新
    //         console.log('当前from未定义');
    //         if(this.$route.query.page){
    //           this.currentPage = Number(this.$route.query.page)
    //         }
    //       }else if(from.path === to.path){
    //         if(this.$route.query.page){
    //           this.currentPage = Number(this.$route.query.page);
    //         }
    //
    //       }else if(from.path !== to.path){
    //         this.currentPage = 1;
    //       }
    //       if (matchingSubColumn) {
    //         this.currentColumnName = matchingSubColumn.name;
    //         this.fetchArticleList(matchingSubColumn.name);
    //         this.fetchArticleTotal(matchingSubColumn.name);
    //       }
    //     }
    //   },
    //   immediate: true,
    // },

  },

  methods: {
    ...mapMutations(["setTotal"]),
    //根据子栏目的名字获取文章列表
    async fetchArticleList(subColumnId) {

      console.log('这里是获取文章的请求');
      console.log(this.currentPage);
      try {
        this.loading = true; // 设置 loading 为 true，表示开始加载
        const apiUrl = "/articles/page";
        const response = await service.get(apiUrl, {
          params: {
            subcolumn_id: subColumnId,
            currentPage: this.currentPage,
          },
        });

        if (response.data.code === 20041) {
          this.articles = response.data.data;
        }
      } catch (error) {
        console.error("API 请求出错:", error);
      } finally {
        this.loading = false; // 设置 loading 为 false，表示加载完成
      }
    },
    // 根据子栏目名字获取文章总数
    async fetchArticleTotal(subColumnId) {
      try {
        const apiUrl = "/articles/count"; //接口地址
        const response = await service.get(apiUrl, {
          //路径参数
          params: {
            subcolumn_id: subColumnId,
          },
        });
        if (response.data.code === 20041) {
          this.setTotal(response.data.data);
        }
      } catch {
        console.log("获取文章总数出错");
      }
    },
    //格式化日期，使其只显示年-月-日
    formatDate(dateString) {
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0"); //将月份填充到两位数，比如5变为05
      const day = date.getDate().toString().padStart(2, "0");
      return `${year}-${month}-${day}`;
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      console.log(this.currentColumnName);

      // 更新路由query参数
      this.$router.push({
        path: this.$route.path,
        query: {
          ...this.$route.query,
          page
        }
      });

      this.fetchArticleList(this.currentColumnName);
    },
    //截断标题
    truncatedTitle(title) {
      const maxLength = 60;
      if (title.length > maxLength) {
        return title.slice(0, maxLength) + "...";
      }
      return title;
    },
  },
};
</script>


<style scoped>
/* 添加你想要的样式 */
.main {
  width: 1100px;
  padding: 10px;
}

.article-list {
  list-style: none;
  padding: 10px; /* 设置ul标签的内边距为0，让li标签紧贴父容器 */
}

.article-item {
  margin-bottom: 10px;
  border-bottom: 1px dashed #ccc; /* 将 border-bottom 设置为虚线并设置颜色 */
}

.article-item a {
  font-size: 15px; /* 调整字体大小 */
  line-height: 2; /* 调整行高 */
}



.publish-date {
  font-size: 14px;
  color: #888;
  float: right; /* 将日期文字右浮动，使其右对齐 */
  margin-right: 1%;
  display: block; /* 让日期文字占据独立的行 */
}

.transfer {
  width: 1100px;
  align-items: center;
  height: 50px;

  margin-top: 20px;
}

a {
  text-decoration: none;
  color: black;
}
</style>
